import {Tool} from "@/utils/tool";

export class UniWebsocket {

    constructor(opt) {
        this.websocket = null;
        this.url = opt.url

        this.status = 'open'
        this.locked = false
        this.heartTimer = null
        this.heartTimeMsecond = 5000
        this.reconnectMsecond = 5500
    }

    /**
     * connectSucccallback
     * connectErrorcallback
     * opencallback
     * meeeagecallback
     * */
    connect(opt) {
        let that = this;
        that.locked = true

        if (that.heartTimer != null) {
            clearInterval(that.heartTimer)
        }
        that.heartTimer = setInterval(function () {
            that.send({type: 'ping'})
        }, that.heartTimeMsecond)

        if (that.websocket != null) {
            that.close()
            that.websocket = null
        }
        this.websocket = uni.connectSocket({
            url: that.url,
            success: function (res) {
                if (opt.connectSuccCallback) {
                    opt.connectSuccCallback(res)
                }
            },
            fail: function (res) {
                console.log('connect err', res)
                if (opt.connectErrorCallback) {
                    opt.connectErrorCallback(res)
                }
            },
            complete: function (res) {
                that.locked = false
            }
        })
        //open
        this.websocket.onOpen(function (res) {
            //console.log('socket open')
            if (opt.openCallback) {
                opt.openCallback(res)
            }
        });

        //message
        this.websocket.onMessage(function (res) {
            if (opt.messageCallback) {
                opt.messageCallback(res)
            }
        })

        //close
        this.websocket.onClose(async function (res) {
            if (that.status != 'close') {
                await Tool.sleep(that.reconnectMsecond)
                if (!that.locked) {
                    that.connect(opt)
                    console.log('close re')
                }
            }
        })

        //error
        this.websocket.onError(async function (res) {
            await Tool.sleep(that.reconnectMsecond)
            if (!that.locked) {
               that.connect(opt)
                console.log('error re')
            }
        })
        return this
    }

    send(val) {
        if (typeof val == 'object') {
            val = JSON.stringify(val)
        }
        return this.websocket.send({
            data: val,
        })
    }

    /**
     * success
     * fail
     * */
    close(opt) {
        this.status = 'close'
        return this.websocket.close(opt);
    }


}